<template>
  <el-form
    :model="form"
    status-icon
    ref="form"
    label-width="100px"
    class="demo-form"
  >
    <!-- <el-form-item label="头像">
      <el-upload
        class="avatar-uploader"
        action="http://39.108.143.183:8181/public/uploadAvatar/"
        :show-file-list="false"
        :with-credentials="true"
        :headers="importHeaders"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="form.avatar" :src="form.avatar" class="avatar" key="form.avatar"/>
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-form-item> -->
    <el-form-item
      label="用户名"
      prop="userName"
      :rules="[{ required: true, message: '用户名不能为空' }]"
    >
      <el-input v-model.number="form.userName"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="form.email"></el-input>
    </el-form-item>
    <el-form-item label="联系方式" prop="phone">
      <el-input v-model="form.phone"></el-input>
    </el-form-item>
    <el-form-item v-if="form.roleId" label="角色">
      <el-select
        v-model="form.roleId"
        placeholder="请选择"
        :disabled="isEditRole"
      >
        <el-option label="viewer" value="0">viewer</el-option>
        <el-option label="admin" value="1">admin</el-option>
        <el-option label="editor" value="2">editor</el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('form')">提交</el-button>
      <el-button @click="resetForm('form')">重置</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
// const mytoken = localStorage.getItem("token");
import { request } from "../../utils";
export default {
  data() {
    return {
      form: {},
      isEditRole: true,
      user: {},
      // importHeaders: { token: mytoken },
    };
  },
  watch: {
    "$store.stata.user": {
      handler(val) {
        this.user = val;
      },
      deep: true,
    },
  },
  created() {
    this.getUserInfo();
  },

  methods: {
    refresh() {
      const obj = this.user;
      const newobj = {};
      for (const item in obj) {
        if (Object.hasOwnProperty.call(obj, item)) {
          if (item == "password") {
            continue;
          }
          if (item == "salt") {
            continue;
          }
          if (item == "role" && obj.role) {
            newobj["roleId"] = obj.role.roleId;
            continue;
          }
          newobj[item] = obj[item] ? obj[item] : "";
        }
      }
      this.form = newobj;
      if (this.form.roleId == "1") {
        this.isEditRole = false;
      } else {
        this.isEditRole = true;
      }
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.editUserOK();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    editUserOK() {
      const newobj = {};
      for (const item in this.form) {
        if (Object.hasOwnProperty.call(this.form, item)) {
          if (item == "roleId") {
            // 用户身份为viewer的用户不传roleId
            if (this.form.roleId == "0") {
              continue;
            }
          }
          newobj[item] = this.form[item] ? this.form[item] : "";
        }
      }
      let url;
      if (this.user.role.roleId != "1") {
        url = this.portInterface.editUserSelf;
      } else {
        url = this.portInterface.editUser;
      }
      this.updateUserInfo(url, newobj);
    },
    updateUserInfo(url, newobj) {
      request({
        method: "PUT",
        url: url,
        data: {
          ...newobj,
        },
      }).then(() => {
        this.$message({
          showClose: true,
          message: "修改成功!",
          type: "success",
        });
        this.getUserInfo();
      });
    },

    getUserInfo() {
      request({
        method: "GET",
        url: this.portInterface.getUserInfo,
        params: {
          userId: localStorage.getItem("userId"),
        },
      }).then((res) => {
        console.log("zct presonalMsg", res);
        this.$store.commit("setUserInfo", res.result);
        this.user = res.result;
        this.refresh();
      });
    },
    // 头像上传
    handleAvatarSuccess(res, file) {
      this.form.avatar = URL.createObjectURL(file.raw);
      // console.log("zct imageUrl", this.form.avatar);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>
<style lang="less" scoped>
/deep/.el-upload {
  border: 1px dashed rgba(0, 0, 0, 0.5);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
/deep/.el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}
.avatar {
  width: 50px;
  height: 50px;
  display: block;
}
</style>